package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.result.Result;
import com.example.entity.mqtt.Mqunit;
import com.example.entity.mqtt.MqunitHis;
import com.example.service.MqunitHisService;
import com.example.mapper.MqunitHisMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 14501
* @description 针对表【mqunit_his】的数据库操作Service实现
* @createDate 2024-04-18 18:32:24
*/
@Service
public class MqunitHisServiceImpl extends ServiceImpl<MqunitHisMapper, MqunitHis> implements MqunitHisService{

    @Resource
    private MqunitHisMapper mqunitHisMapper;

    @Override
    public Result<Map<String,MqunitHis>> queryPageListHis(Integer current,Integer size) {
        try{
            IPage<MqunitHis> config = new Page<>(current, size);
            // 解决当搜索条件为空时，默认查询所有数据
            QueryWrapper<MqunitHis> mqunitHisQueryWrapper = new QueryWrapper<>();
            mqunitHisQueryWrapper.orderByDesc("time");
            IPage<MqunitHis> mqunitHisIPage = this.mqunitHisMapper.selectPage(config, mqunitHisQueryWrapper);
            // 每页展示的数据
            List<MqunitHis> mqunitHisList = mqunitHisIPage.getRecords();
            // 将响应数据填充到map中
            if (mqunitHisList.size()==0){
                return Result.error("暂无数据");
            }
            Map map = new HashMap();
            map.put("pages", mqunitHisIPage.getPages());
            map.put("total", mqunitHisIPage.getTotal());
            map.put("list", mqunitHisList);
            return Result.success(map);
        }catch (Exception e) {
            return Result.error("分页查询异常" + String.valueOf(e),"500");
        }
    }

    @Override
    public Result insert(MqunitHis mqunitHis) {
        try {
            int insert = this.mqunitHisMapper.insert(mqunitHis);
            if (insert>0){
                return Result.success();
            }
            return Result.error("清零添加历史新增失败");
        }catch (Exception e){
            return Result.error("新增发生异常");
        }
    }

    @Override
    public Result<List<MqunitHis>> queryListHis() {
        try {
            QueryWrapper<MqunitHis> mqunitHisQueryWrapper = new QueryWrapper<>();
            mqunitHisQueryWrapper.orderByDesc("time");
            List<MqunitHis> mqunitHisList = this.mqunitHisMapper.selectList(mqunitHisQueryWrapper);
            if (!mqunitHisList.isEmpty()){
                return Result.success(mqunitHisList);
            }
            return Result.error("暂时没有数据");
        }catch (Exception e){
            return Result.error("查询发生异常" + String.valueOf(e),"500");
        }
    }
}




